package com.wuxiaoge.handler;

import com.wuxiaoge.exception.BusinessException;
import com.wuxiaoge.result.ResultBody;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


// $ git remote add origin https://gitee.com/wulaobo/jpa-day1.git
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultBody handleException(HttpServletRequest req, Exception e) {
        // 日志记录异常信息
        log.error("发生异常：", e);
        e.printStackTrace();
        // 根据异常类型返回不同的错误信息
        if (e instanceof ArithmeticException) {
            return ResultBody.error("511","算术异常，请联系管理员");
        } else {
            return ResultBody.error("512","未知异常，请联系管理员");
        }
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResultBody handleBusinessException(BusinessException e) {
        return ResultBody.error(String.valueOf(e.getCode()), e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultBody error(MethodArgumentNotValidException e) {
        log.info(e.getMessage(), e);
        return ResultBody.error("513", e.getBindingResult().getFieldError().getDefaultMessage());
    }

}

